package io.zhengsh.nio;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelDemo3 {

    // FileChannel 读取数据到 buffer 中
    public static void main(String[] args) throws IOException {
        // 创建 FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("C:\\a.txt", "rw");
        FileChannel fileChannel = accessFile.getChannel();

        // 创建 buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(48);

        int byteRead = fileChannel.read(byteBuffer);
        while (byteRead != -1) {
            System.out.println("读取到了： " + byteBuffer);
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                System.out.println((char) byteBuffer.get());
            }
            byteBuffer.clear();
            byteRead = fileChannel.read(byteBuffer);
        }
        fileChannel.close();
        System.out.println("end");
    }
}
